package com.example.auv_660.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class TaskUtils {
    private BufferedWriter bufferedWriterTask;
    private BufferedReader bufferedReaderTask;

    private File checkTaskFile;

    private File checkTaskPath;

    public TaskUtils() {
        createPath(Constants.FILE_PATH);
    }

    public void writeTask(String message) {
        if (!this.checkTaskPath.exists()) {
            createTaskPath(Constants.FILE_PATH);
        }

        createTaskFile(Constants.FILE_PATH);

        try {
            this.bufferedWriterTask.write(message);
            this.bufferedWriterTask.flush();
        } catch (IOException e) {
            realseWriteTask();
        }
    }

    public BufferedReader readTask() {

        String fileTaskName = Constants.FILE_PATH + Constants.FILE_WRITE_TASK_PATH + Constants.TASKINFORMATION + ".txt";

        this.checkTaskFile = new File(fileTaskName);

        if (!this.checkTaskFile.exists()) {
            return null;
        }

        try {
            this.bufferedReaderTask = new BufferedReader(new FileReader(fileTaskName));
        } catch (IOException e) {
            realseReadTask();
        }

        return this.bufferedReaderTask;
    }

    public void realseWriteTask() {
        try {
            if (this.bufferedWriterTask != null) {
                this.bufferedWriterTask.close();
                this.bufferedWriterTask = null;
            }
        } catch (IOException e){

        }
    }

    public void realseReadTask() {
        try {
            if (this.bufferedReaderTask != null) {
                this.bufferedReaderTask.close();
                this.bufferedReaderTask = null;
            }
        } catch (IOException e) {

        }
    }

    private void createPath(String path) {
        File fileTask = new File(path + Constants.FILE_WRITE_TASK_PATH);

        this.checkTaskPath = fileTask;

        if (!fileTask.exists()) {
            fileTask.mkdirs();
        }
    }

    private void createTaskPath(String path) {
        this.checkTaskPath = new File(path + Constants.FILE_WRITE_TASK_PATH);
        this.checkTaskPath.mkdirs();
    }

    private void createTaskFile(String path) {
        String fileTaskName = path + Constants.FILE_WRITE_TASK_PATH + Constants.TASKINFORMATION + ".txt";
        this.checkTaskFile = new File(fileTaskName);

        try {
            this.bufferedWriterTask = new BufferedWriter(new FileWriter(fileTaskName, false));
        } catch (IOException e) {
            realseWriteTask();
        }
    }
}

